//
//  FANDataViewModel.swift
//  Weibo - Swift
//
//  Created by user on 16/4/20.
//  Copyright © 2016年 user. All rights reserved.
//

import UIKit
import SDWebImage
import YYText
import SVProgressHUD

class FANDataViewModel: NSObject {

    var status:FANStatus?{
        
        didSet{
            
            changeMemberImage()
            
            setSourceText()
            
            if let s = status?.retweeted_status {
                
                if let name = s.user?.name , content = s.text{
                    
                    retweetText = "@\(name):\(content)"
                }
            }

            retweetPictureSize = calPictureSize(status?.retweeted_status?.pic_urls)
            originalPictureSize = calPictureSize(status?.pic_urls)
            
            createDate = sinaDate(status?.created_at)
            
            originalAttributeString = self.attributeText(status?.text ?? "")
            retweetAttributeString = self.attributeText(status?.retweeted_status?.text ?? "")
        }
    }
    
    var memberImage:UIImage?
    
    var retweetText:String?
    
    var sourceText:String?
    
    var retweetPictureSize:CGSize = CGSizeZero
    
    var originalPictureSize:CGSize = CGSizeZero
    
    var createDate:NSDate?
    
    var createText:String?{
        
        return dealCreateDate(createDate!)
    }
    
    var originalAttributeString:NSAttributedString?
    var retweetAttributeString:NSAttributedString?

    
    func attributeText(text: String) -> NSAttributedString{
        
        let attributeString = NSMutableAttributedString(string: text)
        
        var results = [FANMatchResult]()
        
        (text as NSString).enumerateStringsMatchedByRegex("\\[[a-zA-Z0-9\\u2E80-\\u9FFF]+\\]") { (count, captureString, captureRange, _) -> Void in
            
            let result = FANMatchResult(captureString: captureString.memory!, range: captureRange.memory)
            
            results.append(result)
        }
        
        for value in results.reverse(){
            
            if let emoticon = FANEmoticonViewModel.sharedEmoticon.emoticonWithChs(value.captureString as String){
                
                let image = UIImage(named:  "\(emoticon.folderName ?? "")/\(emoticon.png ?? "")", inBundle: FANEmoticonViewModel.sharedEmoticon.emoticonBundle, compatibleWithTraitCollection: nil)
                
                let attach = FANTextAttachment()
                
                attach.image = image
                
                let font = UIFont.systemFontOfSize(FANStatusCellContentFontSize)
                
                attach.bounds = CGRectMake(0, -4, font.lineHeight, font.lineHeight)
                
                let attr = NSAttributedString(attachment: attach)
                
                attributeString.replaceCharactersInRange(value.range, withAttributedString: attr)
            }
            
        }
        
        attributeString.addAttribute(NSForegroundColorAttributeName, value: UIColor.darkGrayColor(), range: NSMakeRange(0, attributeString.length))
        
        addLineColor("#[^#]+#", attributeString: attributeString)
        
        addLineColor("@[\\u4e00-\\u9fa5A-Za-z0-9_\\-]+", attributeString: attributeString)

        addLineColor("([hH]ttp[s]{0,1})://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\-~!@#$%^&*+?:_/=<>.',;]*)?", attributeString: attributeString)

        attributeString.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(FANStatusCellContentFontSize), range: NSMakeRange(0, attributeString.length))
        
        return attributeString
    }
    
    func addLineColor(regex:String ,attributeString:NSMutableAttributedString){
        
        (attributeString.string as NSString).enumerateStringsMatchedByRegex(regex) { (count, captureString, captureRange, _) -> Void in
            
            attributeString.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 80/255, green: 125/255, blue: 175/255, alpha: 1), range: captureRange.memory)
            
            let border = YYTextBorder(fillColor: UIColor(red: 177/255, green: 215/255, blue: 255/255, alpha: 1), cornerRadius: 3)
            
            border.insets = UIEdgeInsetsZero
            
            let highlight = YYTextHighlight()
            
            highlight.setColor(UIColor(red: 80/255, green: 125/255, blue: 175/255, alpha: 1))
            
            highlight.setBackgroundBorder(border)
            
            let s = captureString.memory! as NSString
            
            highlight.tapAction = { (containerView: UIView, text: NSAttributedString, range: NSRange, rect: CGRect)->() in
                
                SVProgressHUD.showInfoWithStatus(s as String)
            }
            
            attributeString.yy_setTextHighlight(highlight, range: captureRange.memory)
            
        }
        
    }
    
    func sinaDate(creatAt:String?)->NSDate?{
        
        guard let creat_at = creatAt else{
            
            return nil
        }
        
        let fm = NSDateFormatter()
        
        fm.locale = NSLocale(localeIdentifier: "en")
        
        fm.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        
        let createDate = fm.dateFromString(creat_at)
    
        return createDate
    }
    
    func dealCreateDate(let createDate:NSDate)->String{
        
        let fm = NSDateFormatter()
        
        fm.locale = NSLocale(localeIdentifier: "en")
        
        let calendar = NSCalendar.currentCalendar()
        
//         createDate = NSDate().dateByAddingTimeInterval(-61 * 60 * 24 * 5)

        
        //今年
        if isDateInThisYear(createDate){
            
            if calendar.isDateInToday(createDate){//今天
                
                let currentDate = NSDate()
                
                let timeIn = currentDate.timeIntervalSinceDate(createDate)
                
                if timeIn < 60 {
                    
                    return "刚刚"
                    
                }else if timeIn < 60 * 60 {
                    
                    return "\(Int(timeIn)/60)分钟前"
                    
                }else {
                    
                    return "\(Int(timeIn)/3600)小时前"
                }
                
            }else if calendar.isDateInYesterday(createDate){//昨天
                
                fm.dateFormat = "昨天 HH:mm"
                
                return fm.stringFromDate(createDate)
                
            }else{//其他
                
                fm.dateFormat = "MM-dd HH:mm"
                
                return fm.stringFromDate(createDate)
            }
            
            
        }else{//往年
            
            fm.dateFormat = "yyyy-MM-dd HH:mm"
            
            return fm.stringFromDate(createDate)
        }
        
    }
    
    private func isDateInThisYear(targetDate:NSDate) -> Bool{
        
        let fm = NSDateFormatter()
        
        let currentDate = NSDate()
        
        fm.dateFormat = "yyyy"
        
        let targetYear = fm.stringFromDate(targetDate)
        
        let currentYear = fm.stringFromDate(currentDate)
        
        return targetYear == currentYear
    }
    
    func reloadSinglePicture(){
        
        originalPictureSize = calSinglePictureSize(status?.pic_urls)
        
        retweetPictureSize = calSinglePictureSize(status?.retweeted_status?.pic_urls)
    }
    
    
    func calSinglePictureSize(pic_urls:[FANStatusPicInofo]?) -> CGSize{
        
        guard let imageString = pic_urls?.first?.thumbnail_pic else{
            
            return CGSizeZero
        }
        
        if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(imageString){
            
            let scale = UIScreen.mainScreen().scale
            
            var size = CGSizeMake(image.size.width * scale, image.size.height * scale)
            
            if size.width < 50 {
                // 10 30     size   size*50
                // 50 150    height height * 50
                
                let height = 50 / size.width * size.height
                
                size.width = 50
                
                size.height = size.height > 100 ? 100 : height
            }
            
            return size
            
        }
        
        return CGSizeZero
    }
    
    func calPictureSize(pic_urls:[FANStatusPicInofo]?) -> CGSize{
        
        
        let count = pic_urls?.count ?? 0
        
        if count == 0{
            
            return CGSizeZero
        }
        
        let col = CGFloat((count == 4) ? 2 : ((count > 3) ? 3 : count))
        
        let row = CGFloat((count - 1)/3 + 1)
        
        let viewWidth = FANPictureWH * col + FANPictureMargin * (col - 1)
        
        let viewHeight = FANPictureWH * row + FANPictureMargin * (row - 1)
        
        return CGSizeMake(viewWidth, viewHeight)
    }
    
    func setSourceText(){
        
        //<a href=\"http://app.weibo.com/t/feed/5B6hUc\" rel=\"nofollow\">iPhone 6s Plus</a>
        
        guard let s = status?.source else{
            
            return
        }
        
        if let startIndex = s.rangeOfString("\">")?.endIndex {
            
            if let endIndex = s.rangeOfString("</a")?.startIndex {
                
                let result = s.substringWithRange(startIndex..<endIndex)
                
                sourceText = "来自 \(result)"
            }
        }
    }
    
    func changeMemberImage(){
        
        if let value = status?.user?.mbrank where (value > 0 && value < 7){
            
            memberImage = UIImage(named: "common_icon_membership_level\(value)")
        }
    }
    
}
